import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'


export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd())
  
  // 解析代理配置
  const parseProxyConfig = () => {
    const proxies = {}
    
    // 支持从环境变量读取多个代理配置
    const proxyKeys = Object.keys(env).filter(key => key.startsWith('VITE_PROXY_'))
    
    proxyKeys.forEach(key => {
      try {
        const proxyName = key.replace('VITE_PROXY_', '').toLowerCase()
        const config = JSON.parse(env[key])

        proxies[`/${proxyName}`] = {
          target: config.target,
          changeOrigin: true,
          rewrite: (path) => path.replace(new RegExp(`^/${proxyName}`), ''),
          secure: false,
          headers: {
            'Referer': config.target,
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'
          }
        }
      } catch (e) {
        console.error(`Failed to parse proxy config for ${key}:`, e)
      }
    })
    
    return proxies
  }

  return {
    plugins: [vue()],
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
      },
    },
    server: {
      proxy: parseProxyConfig()
    }
  }
})